package main

import (
	"fmt"
	"sync"
)

var wg sync.WaitGroup

type SafeMap struct {
	data map[int]int
	sync.RWMutex
}

func safeMapMethod1() {
	map1 := SafeMap{data: make(map[int]int, 0)}
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			map1.Lock()
			fmt.Println(i, "lock")
			map1.data[i] = i
			map1.Unlock()
		}(i)
	}
	wg.Wait()
	fmt.Println(map1.data)
}

func safeMapMethod2() {
	map2 := sync.Map{}
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			map2.Store(i, i)
		}(i)
	}
	wg.Wait()
	fmt.Println("map2", map2)
	map2.Range(func(key, value interface{}) bool {
		fmt.Println(key, value)
		return true
	})
}

func main() {
	// safeMapMethod1()
	safeMapMethod2()
}
